/**
 * 文件名：****.java
 * 版权：Copyright Lightkit All Rights Reserved.
 * 描述：*****
 */
package com.lightkits.wms.domain.deliveryorder;

import com.lightkits.framework.common.exception.LightKitsBizException;
import com.lightkits.framework.common.logging.Logger;
import com.lightkits.framework.common.logging.LoggerFactory;
import com.lightkits.framework.common.model.IResult;
import com.lightkits.framework.common.utility.date.DateUtil;
import com.lightkits.framework.common.utility.object.ObjectUtil;
import com.lightkits.framework.common.utility.validate.IntegrityValidator;
import com.lightkits.framework.soa.common.pipeline.session.SessionInfo;
import com.lightkits.framework.soa.hzero.executor.ServiceExecutor;
import com.lightkits.wms.database.dao.WmsDeliveryOrderBaseMapper;
import com.lightkits.wms.database.model.BdDeliveryTaskModel;
import com.lightkits.wms.dto.deliveryorder.QueryDeliverTaskRequestType;
import com.lightkits.wms.dto.deliveryorder.QueryDeliverTaskResponseType;
import com.lightkits.wms.dto.deliveryorder.model.DeliverTaskDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * QueryDeliveryTaskExecutor
 *
 * @author jing.wei@hand-china.com
 * Created on 2019/2/21 16:19
 */
@Component
public class QueryDeliveryTaskExecutor implements
        ServiceExecutor<QueryDeliverTaskRequestType, QueryDeliverTaskResponseType> {
    private final Logger logger = LoggerFactory.getLogger(QueryDeliveryTaskExecutor.class);

    private final WmsDeliveryOrderBaseMapper wmsDeliveryOrderBaseMapper;

    @Autowired
    public QueryDeliveryTaskExecutor(WmsDeliveryOrderBaseMapper wmsDeliveryOrderBaseMapper) {
        this.wmsDeliveryOrderBaseMapper = wmsDeliveryOrderBaseMapper;
    }

    @Override
    public QueryDeliverTaskResponseType service(QueryDeliverTaskRequestType reqeust) {
        QueryDeliverTaskResponseType response = new QueryDeliverTaskResponseType();
        response.setSuccessful(true);
        List<DeliverTaskDTO> deliverTaskDTOS = new ArrayList<DeliverTaskDTO>();
        IResult result = this.checkParams(reqeust);
        if (!result.isSuccessful()) {
            result.fill(response);
            return response;
        }
        List<BdDeliveryTaskModel> models = new ArrayList<BdDeliveryTaskModel>();
        if (!ObjectUtil.isNullOrEmpty(reqeust.getDoNumOrId())) {

            models = wmsDeliveryOrderBaseMapper.queryDeliveryTaskByDoNum(
                    reqeust.getDoNumOrId(), SessionInfo.languageCode());

        } else {
            if (!ObjectUtil.isNullOrEmpty(reqeust.getCompletedDate())) {
                models = wmsDeliveryOrderBaseMapper.queryDeliveryTaskByDate(
                        reqeust.getCompletedDate(), SessionInfo.languageCode());
            } else {
                response.setMessage("the completedDate is null");
                response.setSuccessful(false);
                return response;
            }
        }
        if (ObjectUtil.isNullOrEmpty(models)) {
            response.setSuccessful(true);
            response.setDeliverTasks(deliverTaskDTOS);
            return response;
        }
        models.forEach(target -> {
            DeliverTaskDTO dto = this.getTaskDto(target);
            deliverTaskDTOS.add(dto);
        });
        List<DeliverTaskDTO> deliverTasks;
        //filter by quantity
        if (!reqeust.getSelectParams().equals("ALL")) {
            deliverTasks = deliverTaskDTOS.stream().filter(target ->
                    Integer.valueOf(target.getDeliveryQty()) < Integer.valueOf(target.getDemandQty()))
                    .collect(Collectors.toList());
        } else {
            deliverTasks = deliverTaskDTOS;
        }
        if (ObjectUtil.isNullOrEmpty(deliverTasks)) {
            response.setCurrentDate(reqeust.getCompletedDate());
            response.setDeliverTasks(deliverTasks);
            return response;
        }
        //order by params
        if (reqeust.getOrderParams().equals("QUANTITY")) {
            if (reqeust.getOrderStatus().equals("UP")) {
                deliverTasks.sort((o1, o2) ->
                        Integer.valueOf(o1.getDemandQty()) > Integer.valueOf(o2.getDemandQty()) ? 1 : -1);
            } else {
                deliverTasks.sort((o1, o2) ->
                        Integer.valueOf(o1.getDemandQty()) > Integer.valueOf(o2.getDemandQty()) ? -1 : 1);
            }
        } else {
            List<String> proCode = deliverTasks
                    .stream()
                    .map(DeliverTaskDTO::getPriorityCode).collect(Collectors.toList());
            if (reqeust.getOrderStatus().equals("UP")) {
                deliverTasks.sort(Comparator.comparing(DeliverTaskDTO::getPriorityCode));

            } else {
                deliverTasks.sort(Comparator.comparing(DeliverTaskDTO::getPriorityCode).reversed());
            }
        }

        response.setCurrentDate(reqeust.getCompletedDate());
        response.setMountSize(String.valueOf(deliverTasks.size()));
        response.setPageDataCount(deliverTasks.size());
        response.setDeliverTasks(deliverTasks);
        return response;
    }

    /**
     * 转换实体
     *
     * @param sopDemand 需求订单
     * @return DeliverTaskDTO
     */
    private DeliverTaskDTO getTaskDto(BdDeliveryTaskModel sopDemand) {
        DeliverTaskDTO dto = new DeliverTaskDTO();
        try {
            dto.setDoId(sopDemand.getDoId());
            dto.setDoNumber(sopDemand.getDoNumber());
            dto.setDeliveryQty(sopDemand.getDeliveryQty());
            dto.setDemandQty(sopDemand.getDemandQty());
            dto.setMakeOrderQty(sopDemand.getMakeOrderQty());
            dto.setItemId(sopDemand.getItemId());
            dto.setItemCode(sopDemand.getItemCode());
            dto.setItemDesc(sopDemand.getItemDesc());
            dto.setPrimaryUom(sopDemand.getPrimaryUom());
            dto.setPrimaryUomText(sopDemand.getPrimaryUomText());
            dto.setOrderStatusCode(sopDemand.getOrderStatusCode());
            dto.setOrderStatusText(sopDemand.getOrderStatusText());
            dto.setPriorityCode(sopDemand.getPriorityCode());
            dto.setPriorityText(sopDemand.getPriorityText());
            dto.setCustomerName(sopDemand.getCustomerName());
            dto.setCustomerId(sopDemand.getCustomerId());
            dto.setCustomerItem(sopDemand.getCustomerItem());
            dto.setOrgId(sopDemand.getOrgId());
        } catch (Exception e) {
            logger.error("getTaskDto.error", e);
            throw new LightKitsBizException(e);
        }
        return dto;
    }

    /**
     * 参数校验
     *
     * @param requestType 请求参数
     * @return IResult
     */
    private IResult checkParams(QueryDeliverTaskRequestType requestType) {
        try {
            IntegrityValidator.begin().validate(requestType.getOrderParams(), "Order Params")
                    .validate(requestType.getOrderStatus(), "Order Status")
                    .validate(requestType.getSelectParams(), "Select Params");

            if (!DateUtil.isDate(requestType.getCompletedDate(), DateUtil.DEFAULT_DATE_PATTERN)) {
                return IResult.fail("The Completed Date is Invalid");
            }
        } catch (LightKitsBizException e) {
            return e.result();
        }
        return IResult.success();
    }


}
